package com.drug.mingkang.permission.service.impl;

import com.drug.mingkang.permission.mapper.PerUserRoleMapper;
import com.drug.mingkang.permission.model.PerUserRole;
import com.drug.mingkang.permission.model.PerUsers;
import com.drug.mingkang.permission.mapper.PerUsersMapper;
import com.drug.mingkang.permission.model.vo.PerUsersVo;
import com.drug.mingkang.permission.service.PerUsersService;
import com.drug.mingkang.utils.GiteeImgTools;
import com.drug.mingkang.utils.ResponseMessage;
import com.drug.mingkang.utils.Tools;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 用户表(PerUsers)表服务实现类
 *
 * @author wenchangjian
 * @since 2020-08-11 23:25:01
 */
@Service("perUsersService")
public class PerUsersServiceImpl implements PerUsersService {
    @Resource
    private PerUsersMapper perUsersMapper;

    @Resource
    private Tools tools;

    @Resource
    private ResponseMessage responseMessage;

    @Resource
    private PerUserRoleMapper perUserRoleMapper;

    /**
     * 定义图片类型
     */
    public static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif","image/jpg","image/png");

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public PerUsers queryById(Integer userId) {
        PerUsers perUsers = this.perUsersMapper.queryById(userId);
        return perUsers;
    }

    /**
     * 查询多条数据
     *
     * @param perUsersVo 实例对象
     * @return 对象列表
     */
    @Override
    public Map<String, Object> queryAllByLimit(PerUsersVo perUsersVo) {
        return tools.limit(this.perUsersMapper.queryAllByLimit(perUsersVo),this.count(perUsersVo));
    }

    /**
     * 总条数
     * @param perUsersVo 实例对象
     * @return
     */
    @Override
    public int count(PerUsersVo perUsersVo) {
        return this.perUsersMapper.count(perUsersVo);
    }



    /**
     * 新增数据
     *
     * @param perUsers 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(PerUsers perUsers) {
        return this.perUsersMapper.insert(perUsers);
    }

    @Override
    public ResponseMessage insertSelective(PerUsers perUsers) {
        return this.perUsersMapper.insertSelective(perUsers) > 0 ? ResponseMessage.success("注册成功") : ResponseMessage.error("注册失败");
    }


    /**
     * 修改数据
     *
     * @param perUsers 实例对象
     * @return 实例对象
     */
    @Override
    public ResponseMessage update(PerUsers perUsers) {
        return this.perUsersMapper.update(perUsers) > 0 ? ResponseMessage.success("修改成功") : ResponseMessage.error("修改失败");
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public ResponseMessage deleteById(Integer userId) {
        return this.perUsersMapper.deleteById(userId) > 0 ? ResponseMessage.success("删除成功") : ResponseMessage.error("删除失败");
    }

    @Override
    public PerUsers findUser(String username, String password) {
        return this.perUsersMapper.findUser(username,password);
    }

    /**
     *  用户修改密码
     * @param perUsers
     * @return
     */
    @Override
    public ResponseMessage updatePassword(PerUsers perUsers) {
        return this.perUsersMapper.updatePassword(perUsers) > 0 ? ResponseMessage.success("修改成功") : ResponseMessage.error("修改失败");
    }

    /**
     * 审核用户
     * @param userId
     * @param userName
     * @return
     */
    @Override
    public ResponseMessage auditUser(Integer userId, String userName) {
        return this.perUsersMapper.auditUser(userId, userName) > 0 ? ResponseMessage.success("审核成功") : ResponseMessage.error("审核失败");
    }

    /**
     * 根据用户名查找用户
     * @param userName
     * @return
     */
    @Override
    public PerUsers findUsers(String userName) {
        return perUsersMapper.findUsers(userName);
    }

    @Override
    public ResponseMessage insertAndEdit(PerUsers perUsers, MultipartFile imgFile, HttpSession session, Integer[] roleIdAll) throws Exception {
        //获取登入用户信息
        PerUsers usersSession = (PerUsers) session.getAttribute("perUsers");
        //设置编辑人
        perUsers.setCreatePerson(usersSession.getUserName());
        //图片路径
        String imgFilePath="";
        //判断是否选择了图片
        if(!"".equals(imgFile.getOriginalFilename())) {
            //校验文件类型
            String contentType = imgFile.getContentType();
            if (!CONTENT_TYPES.contains(contentType)) {
                //文件类型不合法,返回null
                System.out.println("文件类型不合法,返回null");
                responseMessage.setStatus(6);
                responseMessage.setMessage("文件类型不合法,返回null");
                return responseMessage;
            }
            //上传图片到图片服务器
            imgFilePath = new GiteeImgTools().saveImg(imgFile);
            //设置图片地址
            perUsers.setUserImg(imgFilePath);
        }
        //判断是增加还是编辑
        if(perUsers.getUserId()==null || "".equals(perUsers.getUserId())){
            //增加用户信息
            responseMessage = perUsersMapper.insertSelective(perUsers) > 0 ? ResponseMessage.success("增加成功") : ResponseMessage.error("增加失败");
            //判断用户是否选择了角色
            if(roleIdAll!=null && !"".equals(roleIdAll)){
                List<PerUserRole> list = new ArrayList<>();
                for (Integer roleId : roleIdAll) {
                    PerUserRole perUserRole = new PerUserRole();
                    perUserRole.setRoleId(roleId);
                    perUserRole.setUserId(perUsers.getUserId());
                    list.add(perUserRole);
                }
                //批量增加用户角色表
                perUserRoleMapper.insertBatch(list);
            }
        }else{
            //根据所编辑的用户ID 删除用户角色模块表所有是这个用户的
            perUserRoleMapper.deleteUsersById(perUsers.getUserId());
            //判断用户是否选择了角色
            if(roleIdAll!=null && !"".equals(roleIdAll)) {
                List<PerUserRole> list = new ArrayList<PerUserRole>();
                for (Integer roleId : roleIdAll) {
                    PerUserRole perUserRole = new PerUserRole();
                    perUserRole.setRoleId(roleId);
                    perUserRole.setUserId(perUsers.getUserId());
                    list.add(perUserRole);
                }
                //批量增加用户角色表
                perUserRoleMapper.insertBatch(list);
            }
            //修改用户信息
            responseMessage = perUsersMapper.update(perUsers) > 0 ? ResponseMessage.success("编辑成功") : ResponseMessage.error("编辑失败");
        }
        return responseMessage;
    }

    @Override
    public ResponseMessage updateBasicInformation(PerUsers perUsers, MultipartFile imgFile, HttpSession session) throws Exception {
        //获取登入用户信息
        PerUsers usersSession = (PerUsers) session.getAttribute("perUsers");
        //设置编辑人
        perUsers.setCreatePerson(usersSession.getUserName());
        //图片路径
        String imgFilePath="";
        //判断是否选择了图片
        if(!"".equals(imgFile.getOriginalFilename())) {
            //校验文件类型
            String contentType = imgFile.getContentType();
            if (!CONTENT_TYPES.contains(contentType)) {
                //文件类型不合法,返回null
                System.out.println("文件类型不合法,返回null");
                responseMessage.setStatus(6);
                responseMessage.setMessage("文件类型不合法,返回null");
                return responseMessage;
            }
            imgFilePath = new GiteeImgTools().saveImg(imgFile);
            perUsers.setUserImg(imgFilePath);
        }
        perUsers.setCreateTime(new Date());
        return perUsersMapper.update(perUsers) > 0 ? ResponseMessage.success("修改成功") : ResponseMessage.error("修改失败");
    }

    /**
     * 删除所选用户
     * @param idAll 用户Id数组
     * @return
     */
    @Override
    public ResponseMessage deleteAllById(String[] idAll) {
        return this.perUsersMapper.deleteAllById(idAll) >= idAll.length ? ResponseMessage.success("删除成功") : ResponseMessage.error("删除失败");
    }

    @Override
    public ResponseMessage resetPassword(String userPassword, String userName) {
        return this.perUsersMapper.resetPassword(userPassword, userName) > 0 ? ResponseMessage.success("重置密码成功") : ResponseMessage.error("重置密码失败");
    }


}